//
//  AlibiTableViewController.m
//  CarHome
//
//  Created by lanou3g on 15-5-2.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "AlibiTableViewController.h"
#import "Alibi.h"
#import "AlibiInfo.h"
#import "Specification.h"
#import "AlibiTableViewCell.h"

@interface AlibiTableViewController ()

@property (nonatomic, retain) UISegmentedControl *segmentedControl;
@property (nonatomic, retain) UILabel *score;
@property (nonatomic, retain) UILabel *participates;
@property (nonatomic, retain) Alibi *alibi;
@property (nonatomic, retain) NSMutableArray *selllist;
@property (nonatomic, retain) NSMutableArray *stoplist;

@end

@implementation AlibiTableViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"AlibiTableViewCell" bundle:nil] forCellReuseIdentifier:@"AlibiTableViewCellIdentifier"];
    
    [self addHeaderView];
    
    self.selllist = [NSMutableArray array];
    self.stoplist = [NSMutableArray array];
}

- (void)addHeaderView {
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 120)] autorelease];;
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fame_icon_fraction"]] autorelease];
    imageView.frame = CGRectMake(20, 20, 50, 50);
    [headerView addSubview:imageView];
    
    self.score = [[[UILabel alloc] initWithFrame:CGRectMake(80, 20, 100, 30)] autorelease];
    _score.font = [UIFont boldSystemFontOfSize:30];
//    _score.text = @"8.8";
    [headerView addSubview:_score];
    
    self.participates = [[[UILabel alloc] initWithFrame:CGRectMake(80, 50, 150, 20)] autorelease];
    _participates.font = [UIFont systemFontOfSize:12];
//    _participates.text = @"123人参与评分";
    _participates.textColor = [UIColor grayColor];
    [headerView addSubview:_participates];
    
    UIImageView *right = [[UIImageView alloc] initWithFrame:CGRectMake(274, 27, 80, 50)];
    right.image = [UIImage imageNamed:@"bg_view"];
    [headerView addSubview:right];
    
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"在售", @"停产"]] ;
    _segmentedControl.frame = CGRectMake(20, 90, kWIDTH - 40, 30);
    _segmentedControl.tintColor = [UIColor blueColor];
    _segmentedControl.selectedSegmentIndex = 0;
    [headerView addSubview:_segmentedControl];
    [_segmentedControl addTarget:self action:@selector(segementControlAction:) forControlEvents:UIControlEventValueChanged];
    
    self.tableView.tableHeaderView = headerView;
}

- (void)loadData {
    if (_selllist.count == 0) {
        NSLog(@"%@", AlibiURLwithCarID(_seriesID));
        __block typeof(self) weakSelf = self;
        
        [HTTPRequest requestWithURL:AlibiURLwithCarID(_seriesID) method:@"GET" result:^(NSData *data) {
            NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            self.alibi = [[Alibi new] autorelease];
            [_alibi setValuesForKeysWithDictionary:dict[@"result"]];
            
            self.selllist = [[NSMutableArray alloc]initWithArray:_alibi.selllist];
            self.stoplist = [[NSMutableArray alloc]initWithArray:_alibi.stoplist];
            
            [weakSelf.tableView reloadData];
        }];
    } else {
        [self.tableView reloadData];
    }
    
}


- (void)segementControlAction:(UISegmentedControl *)sender {
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _segmentedControl.selectedSegmentIndex == 0 ? _selllist.count : _stoplist.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _segmentedControl.selectedSegmentIndex == 0 ? [_selllist[section] specs].count : [_stoplist[section] specs].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AlibiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlibiTableViewCellIdentifier"];
    
    _score.text = [NSString stringWithFormat:@"%@", _alibi.grade];
    _participates.text = [NSString stringWithFormat:@"%@人参与评分", _alibi.peoplenum];
    NSMutableArray *images = [[NSMutableArray alloc] initWithObjects:cell.image1, cell.image2, cell.image3, cell.image4, cell.image5, nil];
    NSMutableArray *selectedArray = nil;
    
    if (_segmentedControl.selectedSegmentIndex == 0) {
        selectedArray = [[NSMutableArray alloc] initWithArray:_selllist];
    } else {
        selectedArray = [[NSMutableArray alloc] initWithArray:_stoplist];
    }
    
    Specification *s = [selectedArray[indexPath.section] specs][indexPath.row];
    NSNumber *scoreNumber = (NSNumber *)s.grade;
    cell.specname.text = s.specname;
    cell.grade.text = [NSString stringWithFormat:@"%@分", scoreNumber];
    cell.peoplenum.text = [NSString stringWithFormat:@"%@人参与评分", s.peoplenum];
    for (int i = 0; i < 5; i++) {
        UIImageView *image = images[i];
        if (i <= [scoreNumber floatValue] - 1) {
            image.image = [UIImage imageNamed:@"star10"];
        } else {
            NSInteger imageNameNumber = ([scoreNumber floatValue] - i) * 10;
            NSString *imageName = [NSString stringWithFormat:@"star%lu", imageNameNumber];
            image.image = [UIImage imageNamed:imageName];
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return _segmentedControl.selectedSegmentIndex == 0 ? [_selllist[section] name] : [_stoplist[section] name];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
